package com.net.xpay.web.controller.merchant.safePay;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.web.vo.BookAccountChargeOrderExVo;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.safePay.BookAccountChargeOrder;
import com.net.xpay.core.manager.safePay.BookAccountChargeOrderManager;
import com.net.xpay.core.model.BookAccountChargeOrderSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**

 */
@RestController
@Slf4j
@RequestMapping("/merchant/safe-pay-book-account-order")
@Api(tags = "商户/安全付充值记录", description = "商户 安全付充值记录 net")
public class BookAccountChargeOrderController {

    @Autowired
    private BookAccountChargeOrderManager bookAccountChargeOrderManager;


    /**
     * 分页
     */
    @ApiOperation("分页")
    @PostMapping("/search")
    public ResultPagedList<BookAccountChargeOrder> search(@ApiIgnore @RequestUser User merchant, @RequestBody BookAccountChargeOrderSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());
        List<BookAccountChargeOrder> records = bookAccountChargeOrderManager.search(searchModel);

        long count = bookAccountChargeOrderManager.searchCount(searchModel);

        return new ResultPagedList<>(records, count, searchModel);
    }
    /**
     * 安全付充值记录导出
     */
    @ApiOperation("安全付充值记录导出")
    @GetMapping("/export")
    public ResultData<Boolean> exportBookAccountChargeOrder(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);
        BookAccountChargeOrderSearchModel searchModel = SerializationUtil.str2Object(searchModelJson,  BookAccountChargeOrderSearchModel.class);
        searchModel.setUserId(merchant.getId());
        long searchCount = bookAccountChargeOrderManager.searchCount(searchModel);
        if (searchCount > 10000L) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "导出数据超过10000条，无法导出");
        }
        List<BookAccountChargeOrder> records = bookAccountChargeOrderManager.list(searchModel);
        List<BookAccountChargeOrderExVo> vos = BeanCopierUtil.batchCopy(BookAccountChargeOrder.class, BookAccountChargeOrderExVo.class, records);
        for (BookAccountChargeOrderExVo vo : vos) {
            if ("AUTO".equals(vo.getSource()) ){
                vo.setShowSource("支付宝余额转入");
            }
            if ("LARGE_DEPOSIT".equals(vo.getSource()) ){
                vo.setShowSource("汇款充值");
            }

            //判断付款账号
            if(Strings.isNullOrEmpty(vo.getPayerIdentity())){
                vo.setShowPayerIdentity(vo.getAlipayNickName());
            }else {
                vo.setShowPayerIdentity(vo.getPayerIdentity() + '\n' + vo.getPayerName());
            }
        }
        if (records.size() > 10000L) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "导出数据超过10000条，无法导出");
        }

        Map<String, Object> model = new HashMap<>();
        model.put("records", vos);

        String fileName = "备付金充值记录.xlsx";
        String template = "/excel/tpl/备付金充值记录.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }

        return new ResultData<>();
    }

}
